﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Collections.Specialized;
using System.Net;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace oneNet
{
    public partial class Form1 : Form
    {
        private String m_FilePath;
        private String m_FileName;
        private String m_Path;
        private String m_url;
        private String API_KEY;
        private int time;
        private static int write_count = 0;
        private Timer timer = new Timer();
        HashSet<string> requestArray = new HashSet<string>();

        public Form1()
        {
            InitializeComponent();
            timer.Tick += timer1_Tick;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*
            string selectedFile="";
            using (var openFileDialog = new OpenFileDialog())
            {
                DialogResult result = openFileDialog.ShowDialog();

                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(openFileDialog.FileName))
                {
                    selectedFile = openFileDialog.FileName;
                }
            }
            if (selectedFile.Equals(""))
            {
                MessageBox.Show("请选择保存文件路径", "ERROR", MessageBoxButtons.OK);
            }
            else
            {
                FilePath = selectedFile;
                filePath.Text = selectedFile;
            }
            */
            string selectedFolder ="";
            using (var folderBrowserDialog = new FolderBrowserDialog())
            {
                DialogResult result = folderBrowserDialog.ShowDialog();

                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
                {
                    selectedFolder = folderBrowserDialog.SelectedPath;
                    Console.WriteLine("Selected folder: " + selectedFolder);
                }
            }
            if (selectedFolder.Equals(""))
            {
                MessageBox.Show("请选择保存文件路径", "ERROR", MessageBoxButtons.OK);
            }
            else {
                m_FilePath = selectedFolder;
                filePath.Text = selectedFolder;
            }
            

        }

        private void filePath_TextChanged(object sender, EventArgs e)
        {
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            m_Path = m_FilePath +"\\" + m_FileName;
        }

        private void FileName_TextChanged(object sender, EventArgs e)
        {
            m_FileName = FileName.Text;
        }
    
        public static void SaveDataToFile(string filePath,float value1,float value2,String device)
        {   

            try
            {
                // 创建目录（如果不存在）
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));

                // 写入数据到文件（追加模式）
                using (StreamWriter writer = new StreamWriter(filePath, true))
                {
                    writer.WriteLine(device + " "+System.DateTime.Now.ToString("F") +" 水总量: " + value1 + ", 水费: " + value2);
                    write_count++;
                    writer.Close();
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存数据错误：" + ex.Message);
            }
            //获取时间
           // MessageBox.Show("保存数据错误：" + DateTimeOffset.UtcNow);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.ShowDialog();

            if (form2.url != null && form2.api_key != null && form2.uniqueNames.Count !=0 ) {
                m_url = form2.url;
                API_KEY = form2.api_key;
                textBox1.Text = m_url;
                textBox2.Text = API_KEY;
                requestArray = form2.uniqueNames;
            }
            if (form2.time != 0)
            {
                time = form2.time;
                label1.Text = time.ToString();
            }
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            m_url = textBox1.Text;
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            API_KEY = textBox2.Text;
        }

        private void Get(String url)
        {
            //string url = textBox1.Text;//设备地址
            string api_key = textBox2.Text;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            SetHeaderValue(request.Headers, "authorization", "version=2022-05-01&res=userid%2F367380&et=1730730167&method=sha1&sign=M5dYuxvsz78fsT2xybso%2F7KAKzQ%3D");
            //"version=2022-05-01&res=userid%2F367380&et=1714743546&method=sha1&sign=uaubi%2FmTAU2FUlyrh4ssfyjmsfM%3D");//设备API地址和 首部参数
            request.Host = "iot-api.heclouds.com";
            request.ProtocolVersion = new Version(1, 1);
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            string[] parameters = url.Split('?')[1].Split('&');

            // 查找设备名称参数
            string deviceNameParameter = parameters.FirstOrDefault(p => p.StartsWith("device_name="));

            // 从设备名称参数中提取设备名称
            string deviceName = deviceNameParameter.Split('=')[1];

            // 打印设备名称
            Console.WriteLine("设备名称：{0}", deviceName);
            GetValue(deviceName, retString);
        }
        // HTTP协议报文头加入
        public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }
        }

        private  void GetValue(string device,string jsonString)
        {   
            Console.WriteLine($"{device}:{jsonString}");
            dynamic jsonObject = JsonConvert.DeserializeObject<dynamic>(jsonString);
            float flow_value, total_value;
            flow_value = total_value = 0;
            bool isEmpty = (jsonObject.data == null);
            if (isEmpty) {
                MessageBox.Show("ERR String" + jsonString);
                return;
            }
            try
            {   
                if (!isEmpty)
                {
                    foreach (var item in jsonObject.data)
                    {
                        string identifier = item.identifier;
                        if (identifier.Equals("flow"))
                        {
                            if (item.value != null)
                            {
                                flow_value = item.value;
                            }
                        }
                        else if (identifier.Equals("total"))
                        {
                            if (item.value != null)
                            {
                                total_value = item.value;
                            }
                        }
                        else
                        {
                            Console.WriteLine("do nothing\n");
                        }
                    }
                }
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine(e.ToString());
            }
            SaveDataToFile(m_Path, flow_value, total_value, device);
        }
        private void setWriteCount() {
            if (m_Path == null)
            {
                return;
            }
            using (FileStream fs = new FileStream(m_Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (StreamReader sr = new StreamReader(fs))
            {
                string line = "";
                // 读取末行
                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine();
                }
                Console.WriteLine("line:"+line+"---");
                if (!line.Equals(""))
                {
                    string[] words = line.Split(' '); // 使用空格分割字符串
                    Console.WriteLine(words[0]);
                    string numericPart = words[0].Substring(4); // 假设数字位于索引位置 4 之后
                    int number = int.Parse(numericPart);
                    Console.WriteLine(number);
                    write_count = number + 1;
                }
                else {
                    write_count = 1;
                }
                
                
                sr.Close();
                fs.Close();
            }
            //string input = "2024年4月27日 8:33:29 test7 水总量: 0, 水费: 0";
            

        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            string text = label1.Text;
            int interval;
            if (int.TryParse(text, out interval))
            {
                timer.Interval = interval * 1000;
            }
            else
            {
                MessageBox.Show("刷新时间获取失败!");
            }
            foreach (string requests in requestArray)
            {
                Console.WriteLine(requests);
                Get(requests);
            }
        }
        
        private void button4_Click(object sender, EventArgs e)
        {
            label5.Text = "demo运行中.....";
            
            timer.Start();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            label5.Text = "demo已暂停";
            timer.Stop();
        }
    }
}
